/**
 * @this FormItemHOC: hook FormItem
 *
 * 可以移植的 Form
 *
 * @flow
 */
import React, { Component } from 'react'
import PropTypes from 'prop-types'

import RXValidateFailAnimate from './ValidateFailAnimate'

import FormItemManager from './FormItemManager'
import ValidationType from '../config/FormItemValidationType'
import FormItemType from '../config/FormItemType'

export default (WrappedComponent) => {
  return class PackComponent extends Component {
    static propTypes = {
      ...WrappedComponent.propTypes,
      formItemType: PropTypes.oneOf(FormItemType.AllTypes()),
      validators: PropTypes.arrayOf(PropTypes.oneOfType([
        PropTypes.func,
        PropTypes.oneOf(ValidationType.AllTypes())// 允许输入的`长度`，看`TextInput封装`实现
      ])),
      hits: PropTypes.array,
      onChange: PropTypes.func,
      failAnimate: PropTypes.bool, // 动画 是否生效
      weakValidator: PropTypes.bool, // 弱化--验证，当value=null/空...的时候，验证不生效
    }

    static defaultProps = {
      ...WrappedComponent.defaultProps,
      weakValidator: false,
    }

    constructor(props) {
      super(props)
      this.state = {
        showTip: false,
        hit: null,
      }
    }

    _doFailAnimate = (params = {}) => {
      const index = params.index || '-1'
      const tip = params.tip || false
      if (this.props.failAnimate) {
        index === this.props.index && this._onAnimate()
      }
      if (tip) {
        const hit = params.hit || '该信息不能为空'
        this.setState({ showTip: true, hit })
      }
    }

    doCloseTip = () => {
      this.setState({ showTip: false })
    }

    _onChange = (value) => {
      this._setValue(value)
      const { onChange } = this.props
      onChange && onChange(value)
    }

    _onAnimate = () => {
      this.anim.startAnimation()
    }

    _setValue(value) {
      const { index, validators } = this.props
      validators && FormItemManager.updateValue(this.props.form.formName, value, index)
    }

    render() {
      return (
        <RXValidateFailAnimate ref={(e) => { this.anim = e }}>
          <WrappedComponent {...this.props} onChange={this._onChange} showTip={this.state.showTip} hit={this.state.hit} doCloseTip={() => this.doCloseTip()}/>
        </RXValidateFailAnimate>
      )
    }
  }
}
